import json
import copy
import time
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *
import logging
import pandas as pd
import requests

activity_battlepass_project_api = Blueprint('activity_battlepass_project_api', __name__)
activity_battlepass_project_down_api = Blueprint('activity_battlepass_project_down_api', __name__)


@activity_battlepass_project_api.route('/activity_battlepass', methods=['POST'])
def activity_battlepass_project():
    params = json.loads(request.data)

    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'detail':
        query = ActivityBattlepass.query.filter_by(project=_project).first()
        tmp = {
            "project": int(query.project),
            'basic': json.loads(query.basic),
            'detail': json.loads(query.detail)
        }
        result_data['data']['item'] = tmp

    elif _action == 'doc_id_list':
        result = get_doc_id_list_in_operation_event_english('activity_card_event', 'title')
        return jsonify(result)

    elif _action == 'get_iap_list':
        result = [
            {
                'value': 0,
                'label': '免费 - 0'
            }
        ]
        with open(STATIC_PATH + '/iap_list.json', 'r') as f:
            iap_list = json.load(f)
            for i in iap_list:
                result.append({
                    'value': i['gem'],
                    'label': f"{i['label']} - {i['gem']}"
                })
        return jsonify(result)

    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']

        if _part == 'basic':
            query = ActivityBattlepass.query.filter_by(project=_project).first()
            query.basic = json.dumps(_data)
        elif _part == 'goal':
            query = ActivityBattlepass.query.filter_by(project=_project).first()
            detail = json.loads(query.detail)
            detail['goal_reward'] = _data
            query.detail = json.dumps(detail)
        elif _part == 'extra':
            query = ActivityBattlepass.query.filter_by(project=_project).first()
            detail = json.loads(query.detail)
            detail['extra_reward'] = _data
            query.detail = json.dumps(detail)
        db.session.commit()
        result_data['data']['msg'] = "更新成功"

    return jsonify(result_data)


@activity_battlepass_project_down_api.route('/activity_battlepass_down/<int:is_push>', methods=['GET', 'POST'])
def activity_battlepass_project_down(is_push):
    activity_battlepass_event_project = {}

    query = ActivityBattlepass.query.order_by('project').all()

    for q in query:
        project = int(q.project)
        basic = json.loads(q.basic)
        detail = json.loads(q.detail)

        goal_reward = {
            'basic': [],
            'elite': []
        }
        for i in detail['goal_reward']:
            goal_reward['basic'].append({
                'reward': RewardToTMysqlNew(i['basic']),
                'show_lv': i['show_lv'],
                'special_lv': i['show_lv']
            })
            goal_reward['elite'].append({
                'reward': RewardToTMysqlNew(i['elite']),
                'show_lv': i['show_lv'],
                'special_lv': i['show_lv']
            })

        activity_battlepass_event_project[str(project)] = {
            '_tag': basic['_tag'],
            '_remark': q.remark,
            'basic': {
                'lv_up_points': basic['lv_up_points'],
                'doc_id': basic['doc_id']
            },
            'extra_reward': {
                'basic': {
                    'delta_lv': detail['extra_reward']['normal']['delta_lv'],
                    'reward': RewardToTMysqlNew(detail['extra_reward']['normal']['reward'])
                },
                'elite': {
                    'delta_lv': detail['extra_reward']['elite']['delta_lv'],
                    'reward': RewardToTMysqlNew(detail['extra_reward']['elite']['reward'])
                }
            },
            'basic_gem': basic['basic_gem'],
            'goal_reward': goal_reward
        }
    if is_push == 0:
        response = DownLoad('activity_battlepass_event_project', activity_battlepass_event_project, 0)
    if is_push == 1:
        r1 = DownLoad('activity_battlepass_event_project', activity_battlepass_event_project, 1)
        if r1:
            return jsonify({"msg": "发布成功", "ret": 1})
        else:
            return False
    return response
